//
//  FMDBManager.m
//
//  Created by 周成龙
//

#import "FMDBManager.h"

#import "FMDB.h"
#import "MainModel.h"

extern NSString *const kTableName;
@implementation FMDBManager
FMDBManager *_instance;
FMDatabase  *_db;

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[FMDBManager alloc] init];
    });
    return _instance;
}

- (instancetype)init {
    if (self = [super init]) {
        
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"sk_db.sqlite"];
        _db = [FMDatabase databaseWithPath:filePath];
        
        if ([_db open]) {
            // 初始化数据表
            NSString *sql = [NSString stringWithFormat:@"create table if not exists %@ ('sid' text not NULL primary key, 'uid' text, 'udid_unique' text, 'content' text, 'img_url' text, 'create_time' text, 'update_time' text, 'alert_time' text, 'status' text)", kTableName];
            [_db executeUpdate:sql];
            [_db close];
        }
        [_db close];
    }
    return self;
}

/**
 存储
 */
- (void)saveObject:(MainModel *)model {
    
    if ([self getObjectById:model.sid] == nil) {
        if ([_db open]) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:model.img_url options:NSJSONWritingPrettyPrinted error:nil];
            NSString *dataString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSString *sql = [NSString stringWithFormat:@"insert into '%@' (sid, uid, udid_unique, content, img_url, create_time, update_time, alert_time, status) values ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@')", kTableName, model.sid, model.uid, model.unique, model.content, dataString, model.create_time, model.update_time, model.alert_time, model.status];
            [_db executeUpdate:sql];
            [_db close];
        }
    }else {
        [self updateObjectById:model];
    }
    [_db close];
}
/**
 根据id删数据
 */
- (void)deleteObjectById:(NSString *)objectId {
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where sid = %@", kTableName, objectId];
        [_db executeUpdate:sql];
        [_db close];
    }
    [_db close];
}
/**
 更新
 */
- (void)updateObjectById:(MainModel *)model {
    if ([self getObjectById:model.sid] == nil) {
        [self saveObject:model];
    }else {
        if ([_db open]) {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:model.img_url options:NSJSONWritingPrettyPrinted error:nil];
            NSString *dataString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSString *sql = [NSString stringWithFormat:@"update %@ set uid='%@', udid_unique='%@', content='%@', img_url='%@', create_time='%@', update_time='%@', alert_time='%@', status='%@' where sid = %@", kTableName, model.uid, model.unique, model.content, dataString, model.create_time, model.update_time, model.alert_time, model.status, model.sid];
            [_db executeUpdate:sql];
            [_db close];
        }
    }
    [_db close];
}
/**
 通过 id 获取存储数据
 */
- (MainModel *)getObjectById:(NSString *)objectId {
    
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"select * from '%@' where sid='%@'", kTableName, objectId];
        FMResultSet *res = [_db executeQuery:sql];
        
        MainModel *model;
        while ([res next]) {
            model = [[MainModel alloc] init];
            model.sid = [res stringForColumn:@"sid"];
            model.uid = [res stringForColumn:@"uid"];
            model.unique = [res stringForColumn:@"udid_unique"];
            model.content = [res stringForColumn:@"content"];
            NSString *dataStr = [res stringForColumn:@"img_url"];
            NSData* data= [dataStr dataUsingEncoding: NSUTF8StringEncoding];
            model.img_url = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            model.create_time = [res stringForColumn:@"create_time"];
            model.update_time = [res stringForColumn:@"update_time"];
            model.alert_time = [res stringForColumn:@"alert_time"];
            model.status = [res stringForColumn:@"status"];
        }
        
        [_db close];
        return model;
    }
    [_db close];
    return nil;
}
/**
 查询数据库所有数据
 */
- (NSArray *)getAllItemsFromTable {
    if ([_db open]) {
        
        NSMutableArray *dataArray = @[].mutableCopy;
        NSString *sql = [NSString stringWithFormat:@"select * from %@", kTableName];
        FMResultSet *res = [_db executeQuery:sql];
        
        while ([res next]) {
            MainModel *model = [[MainModel alloc] init];
            
            model.sid = [res stringForColumn:@"sid"];
            model.uid = [res stringForColumn:@"uid"];
            model.unique = [res stringForColumn:@"udid_unique"];
            model.content = [res stringForColumn:@"content"];
            NSString *dataStr = [res stringForColumn:@"img_url"];
            NSData* data= [dataStr dataUsingEncoding: NSUTF8StringEncoding];
            model.img_url = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            model.create_time = [res stringForColumn:@"create_time"];
            model.update_time = [res stringForColumn:@"update_time"];
            model.alert_time = [res stringForColumn:@"alert_time"];
            model.status = [res stringForColumn:@"status"];
            
            [dataArray addObject:model];
        }
        
        [_db close];
        return [dataArray copy];
    }
    [_db close];
    return nil;
}
/**
 根据uid查询
 */
- (NSArray *)getItemsFromTableWithUid:(NSString *)uid {
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"select * from '%@' where uid='%@'", kTableName, uid];
        FMResultSet *res = [_db executeQuery:sql];
        
        NSMutableArray *dataArray = @[].mutableCopy;
        while ([res next]) {
            MainModel *model = [[MainModel alloc] init];
            
            model.sid = [res stringForColumn:@"sid"];
            model.uid = [res stringForColumn:@"uid"];
            model.unique = [res stringForColumn:@"udid_unique"];
            model.content = [res stringForColumn:@"content"];
            NSString *dataStr = [res stringForColumn:@"img_url"];
            NSData* data= [dataStr dataUsingEncoding: NSUTF8StringEncoding];
            model.img_url = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            model.create_time = [res stringForColumn:@"create_time"];
            model.update_time = [res stringForColumn:@"update_time"];
            model.alert_time = [res stringForColumn:@"alert_time"];
            model.status = [res stringForColumn:@"status"];
            
            [dataArray addObject:model];
        }
        
        [_db close];
        return [dataArray copy];
    }
    [_db close];
    return nil;
}
/**
 根据unique查询
 */
- (NSArray *)getItemsFromTableWithUnique:(NSString *)unique {
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"select * from '%@' where udid_unique='%@'", kTableName, unique];
        FMResultSet *res = [_db executeQuery:sql];
        
        NSMutableArray *dataArray = @[].mutableCopy;
        while ([res next]) {
            MainModel *model = [[MainModel alloc] init];
            
            model.sid = [res stringForColumn:@"sid"];
            model.uid = [res stringForColumn:@"uid"];
            model.unique = [res stringForColumn:@"udid_unique"];
            model.content = [res stringForColumn:@"content"];
            NSString *dataStr = [res stringForColumn:@"img_url"];
            NSData* data= [dataStr dataUsingEncoding: NSUTF8StringEncoding];
            model.img_url = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            model.create_time = [res stringForColumn:@"create_time"];
            model.update_time = [res stringForColumn:@"update_time"];
            model.alert_time = [res stringForColumn:@"alert_time"];
            model.status = [res stringForColumn:@"status"];
            
            [dataArray addObject:model];
        }
        
        [_db close];
        return [dataArray copy];
    }
    [_db close];
    return nil;
}
/**
 清空表中数据
 */
- (void)clearTable {
    if ([_db open]) {
        NSString *sql = [NSString stringWithFormat:@"delete from '%@';", kTableName];
        [_db executeUpdate:sql];
        [_db close];
    }
    [_db close];
}

@end
